﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using System.Collections.Specialized;
using Mvc.XForms.Utilities;

namespace Mvc.XForms.UI {
	public class LinqPagedSortedList<T> : PagedSortedList<T> {
		private IQueryable<T> source;

		// Empty constructor so inherited objects can determine init order
		public LinqPagedSortedList() { }

		public LinqPagedSortedList(IQueryable<T> source, NameValueCollection collection, string pageIndexKey, string sortExpressionKey, string sortDirectionKey, int pageSize, Expression<Func<T, object>> defaultSort, SortDirection defaultSortDirection)
			: this(source, collection, pageIndexKey, sortExpressionKey, sortDirectionKey, pageSize, defaultSort.Body.ExtractID(), defaultSortDirection) { }

		public LinqPagedSortedList(IQueryable<T> source, NameValueCollection collection, string pageIndexKey, string sortExpressionKey, string sortDirectionKey, int pageSize, string defaultSortExpression, SortDirection defaultSortDirection)
			: this(source, new PagedSortedParameters(collection, pageIndexKey, sortExpressionKey, sortDirectionKey, pageSize, defaultSortExpression, defaultSortDirection)) { }

		public LinqPagedSortedList(IQueryable<T> source, IPagedSortedParameters gridParams) {
			this.source = source;
			InitWithParams(gridParams);
		}

		public LinqPagedSortedList(IQueryable<T> source, int pageIndex, int pageSize, string sortExpression, SortDirection sortDirection) {
			this.source = source;
			Init(pageIndex, pageSize, sortExpression, sortDirection);
		}

		protected override int GetTotalCount() {
			var count = source.Count();
			return count;
		}

		protected override void ApplyPaging() {
			var pagedSource = source
				.Page(PageIndex, PageSize)
				.ToList();

			Items = pagedSource;
		}

		protected override void ApplySorting() {
			source = source.Sort(SortExpression, SortDirection);
		}
	}
}